package zh.demo.datasource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zhangheng on 2017/10/30.
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    private final int dataSourceNumber;
    private AtomicInteger count = new AtomicInteger(0);

    public DynamicDataSource(int dataSourceNumber) {
        this.dataSourceNumber = dataSourceNumber;
    }

    @Override
    protected Object determineCurrentLookupKey() {
        String typeKey = DynamicDataSourceHolder.getJdbcType();
        if (typeKey.equals(DynamicDataSourceGlobal.write.getType()))
            return DynamicDataSourceGlobal.write.getType();
        // 读 简单负载均衡
        int number = count.getAndAdd(1);
        int lookupKey = number % dataSourceNumber;
        return new Integer(lookupKey);
    }

    /*private Object writeDataSource;
    private Object readDataSource;

    @Override
    public void afterPropertiesSet(){
        if(this.writeDataSource == null){
            throw new IllegalArgumentException("property 'writeDataSource' is required");
        }
        setDefaultTargetDataSource(writeDataSource);
        Map<Object, Object> targetDataSourceMap = new HashMap<>();
        targetDataSourceMap.put(DynamicDataSourceGlobal.WRITE.name(),writeDataSource);
        if(readDataSource != null){
            targetDataSourceMap.put(DynamicDataSourceGlobal.READ.name(),readDataSource);
        }
        setTargetDataSources(targetDataSourceMap);
        super.afterPropertiesSet();

    }

    @Override
    protected Object determineCurrentLookupKey() {
        DynamicDataSourceGlobal dynamicDataSourceGlobal = DynamicDataSourceHolder.getDataSource();
        if(dynamicDataSourceGlobal == null || dynamicDataSourceGlobal == DynamicDataSourceGlobal.WRITE){
            return DynamicDataSourceGlobal.WRITE.name();
        }
        return DynamicDataSourceGlobal.READ.name();
    }

    public Object getWriteDataSource() {
        return writeDataSource;
    }

    public void setWriteDataSource(Object writeDataSource) {
        this.writeDataSource = writeDataSource;
    }

    public Object getReadDataSource() {
        return readDataSource;
    }

    public void setReadDataSource(Object readDataSource) {
        this.readDataSource = readDataSource;
    }*/
}
